package com.tanhua.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.tanhua.admin.service.AdminService;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/system/users")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /*
     * 获取验证码图片:
     *   GET /verification
     *   请求参数(Query)：
     *           Query uuid(浏览器生成的唯一标志)
     * 返回值(void)：
     *   输出流输出图片的字节流
     * */
    @GetMapping("/verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {
        //1.生成验证码对象(hotool)
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(299, 97);
        //2。获取验证码
        String code = lineCaptcha.getCode();
        //3.存入redis
        redisTemplate.opsForValue().set("CODE"+uuid,code,3, TimeUnit.MINUTES);
        //4.响应验证码图片（把图片写入响应对象中）
        lineCaptcha.write(response.getOutputStream());//相应数据流
    }


    /*
    * 用户登录：
    *   POST  /login
    * 参数：
    *       Body username,password,verificationCode,uuid
    * 返回值：token
    *
    * */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){
        //1.获取请求参数
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        String code = map.get("verificationCode").toString();
        String uuid = map.get("uuid").toString();
        //2.调用service
        Map retMap = adminService.login(username,password,code,uuid);
        //3.返回
        return ResponseEntity.ok(retMap);

    }

    /*
    * 用户基本信息
    *       POST /profile
    * 参数：
    *
    * 返回值： adminVo
    *
    * */
    @PostMapping("/profile")
    public ResponseEntity profile(){
        AdminVo vo = adminService.profile();
        return ResponseEntity.ok(vo);
    }


    /**
     * 用户登出
     * POST /logout
     */
    @PostMapping("logout")
    public void logOut(HttpServletResponse response) throws Exception {
        response.setHeader("Authorization","");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("退出登录成功!");
    }

}
